package demo3;

public class BinarySearchTree {
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int val) {
            this.val = val;
        }
    }

    TreeNode root;

    public boolean search(int key) {
        TreeNode cur = root;
        while(cur!=null) {
            if(cur.val>key) {
                cur = cur.left;
            }else if(cur.val<key) {
                cur = cur.right;
            }else {
                return true;
            }
        }
        return false;
    }

    public boolean insert(int key) {
        if(root == null) {
            root = new TreeNode(key);
            return true;
        }

        TreeNode cur = root;
        TreeNode parent = null;
        while(cur!=null) {
            parent = cur;
            if(cur.val>key) {
                cur = cur.left;
            }else if(cur.val<key) {
                cur = cur.right;
            }else {
                return false;
            }
        }
        if(parent.val > key) {
            parent.left = new TreeNode(key);
        }else {
            parent.right = new TreeNode(key);
        }
        return true;
    }

    public boolean remove(int key) {
        TreeNode cur = root;
        TreeNode parent = null;
        while(cur!=null) {
            parent = cur;
            if(cur.val>key) {
                cur = cur.left;
            }else if(cur.val<key) {
                cur = cur.right;
            }else {
                removeNode(cur,parent);
                return true;
            }
        }
        return false;
    }

    private void removeNode(TreeNode cur, TreeNode parent) {
        if(cur.left == null) {
            if(cur == root) {
                root = cur.right;
            }else if(parent.left== cur) {
                parent.left = cur.right;
            }else if(parent.right == cur) {
                parent.right = cur.right;
            }
        }else if(cur.right == null) {
            if(cur == root) {
                root = cur.left;
            }else if(parent.left == cur) {
                parent.left = cur.left;
            }else if(parent.right == cur) {
                parent.right = cur.left;
            }
        }else {
            TreeNode tmp = cur.right;
            TreeNode tmpParent = cur;
            while(tmp.left!=null) {
                tmpParent = tmp;
                tmp = tmp.left;
            }

            cur.val = tmp.val;
            if(tmpParent.left == tmp) {
                tmpParent.left = tmp.right;
            }else {
                tmpParent.right = tmp.right;
            }
        }
    }
}
